//
//  KNewsGeneralDetailController.m
//  Keping
//
//  Created by a on 2017/9/15.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "KNewsGeneralDetailController.h"
#import "KGeneralCommentsController.h"
#import "KGeneralCommentsVC.h"
#import <MJRefresh/MJRefresh.h>
#import "KBbsTopicsDetailRequest.h"
#import "KGeneralDetailViewCell.h"
#import "KBbsTopicView.h"
#import "KbbsTopicsModel.h"
#import "KGeneralDetailViewFrame.h"
#import "ZMZWebContentView.h"

@interface KNewsGeneralDetailController ()<UITableViewDelegate,UITableViewDataSource,KGeneralDetailViewCellDelegate, UITextFieldDelegate, WKNavigationDelegate>{
    NSInteger pageNum;
    CGSize size;
}

/**web*/
@property(nonatomic,weak)ZMZWebContentView *webBaseView;
@property(nonatomic,weak)UIScrollView *scrollview;
/**table*/
@property(nonatomic,weak)UITableView*tableView;
/**头部*/
@property(nonatomic,weak)UIView*headerView;
/**底部评论框*/
@property(nonatomic,weak)UITextField*commentField;
@property (nonatomic, weak) UILabel *titleLabel;
@property (nonatomic, weak) UIButton *zanBtn;
@property (nonatomic, weak) UILabel *zanLabel;
@property (nonatomic, weak) UILabel *timeLabel;
/**公告模型*/
@property(nonatomic,strong)KBbsTopicView *topicViews;
/**视图模型*/
@property(nonatomic,strong)NSMutableArray<KBbsPostsViews *> *bbsPostsViews;
@property (nonatomic, copy) NSString *commentID;
@end

@implementation KNewsGeneralDetailController

- (NSMutableArray<KBbsPostsViews *> *)bbsPostsViews {
    if (!_bbsPostsViews) {
        _bbsPostsViews = [[NSMutableArray alloc] init];
    }
    return _bbsPostsViews;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
    pageNum = 1;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self getData];
}

-(void)setUI
{
    self.view.backgroundColor= [UIColor colorWithHexString:@"#f2f2f2"];
    self.navigationItem.title=@"News";
    
    //头部网页
    UIView*headerView=[[UIView alloc] init];
    headerView.backgroundColor = kWhiteColor;
    self.headerView=headerView;
    
    UILabel *title = [[UILabel alloc] init];
    title.font = HJFont(K_FactorW(17));
    title.numberOfLines = 0;
    [self.headerView addSubview:title];
    self.titleLabel = title;
    
    UILabel *time = [[UILabel alloc] init];
    time.font = HJFont(K_FactorW(13));
    time.textColor = [UIColor colorWithHexString:@"#9a9a9a"];
    [self.headerView addSubview:time];
    self.timeLabel = time;
    
    UILabel *zancount = [[UILabel alloc] init];
    zancount.font = HJFont(13);
    zancount.textColor = [UIColor colorWithHexString:@"#9a9a9a"];
    [self.headerView addSubview:zancount];
    self.zanLabel = zancount;
    
    UIButton *zan = [[UIButton alloc] init];
    [zan setImage:[UIImage imageNamed:@"like1"] forState:UIControlStateNormal];
    [zan setImage:[UIImage imageNamed:@"like"] forState:UIControlStateSelected];
    zan.selected = NO;
    [zan addTarget:self action:@selector(actionForZan:) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:zan];
    self.zanBtn = zan;
    
    CGRect rect = (CGRect){{0,CGRectGetMaxY(self.timeLabel.frame) + 20},{kScreenWidth,1}};
    WEAKSELF
    ZMZWebContentView *webView = [[ZMZWebContentView alloc] initWithFrame:rect];
    webView.userInteractionEnabled = NO;
    webView.backgroundColor = kWhiteColor;
    [webView setShouldStartLoadBlock:^BOOL(WKWebView *webView, NSURLRequest *request) {
        return YES;
    }];
    [webView setContentHeightBlock:^(CGFloat height) {
        weakSelf.webBaseView.height = height;
        weakSelf.headerView.height = height + 93;
        [weakSelf.tableView reloadData];
    }];
    self.webBaseView = webView;
    [self.headerView addSubview:webView];
    
    //底部评论table
    UITableView*tableView=[[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
    tableView.delegate=self;
    tableView.dataSource=self;
    tableView.backgroundColor=[UIColor colorWithHexString:@"#f2f2f2"];
    [self.view addSubview:tableView];
    self.tableView=tableView;
    tableView.tableHeaderView=headerView;
    tableView.mj_footer = [MJRefreshFooter footerWithRefreshingBlock:^{
        pageNum += 1;
        [weakSelf getGeneralData];
    }];
    
    //地图评论输入框
    UITextField*commentField=[[UITextField alloc]init];
    [self.view addSubview:commentField];
    commentField.placeholder=@"write a comment";
    commentField.layer.masksToBounds=YES;
    commentField.layer.borderColor=[UIColor colorWithHexString:@"#c1c1c1"].CGColor;
    commentField.layer.borderWidth=1;
    commentField.delegate = self;
    commentField.returnKeyType = UIReturnKeySend;
    commentField.leftView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 25, 40)];
    commentField.leftViewMode=UITextFieldViewModeAlways;
    self.commentField=commentField;
}
-(void)getData
{
    [super getData];
    [self showLoading];
    
    WEAKSELF
    NSMutableArray *array = [NSMutableArray new];
    __block KBbsTopicsDetailRequest* bbsTopicsRequest =[[KBbsTopicsDetailRequest alloc]initWithTopicId:self.bbsTopicViewsID];
    __block KBbsGeneralDetailRequest *bbsGeneralRequest;
    __block KBbsGeneralCommentsRequest *bbsGeneralPostRequest;
    [array addObject:bbsTopicsRequest];
    if (self.isBbsPosts) {
        bbsGeneralPostRequest = [[KBbsGeneralCommentsRequest alloc] init];
        bbsGeneralPostRequest.params = @{@"postsId":self.bbsTopicViewsID};
        [array addObject:bbsGeneralPostRequest];
    } else {
        bbsGeneralRequest = [[KBbsGeneralDetailRequest alloc] init];
        bbsGeneralRequest.params = @{@"pageOn":@"1",@"pageSize":@"10",@"topicId":self.bbsTopicViewsID};
        [array addObject:bbsGeneralRequest];
    }
    
    KBatchRequest *request = [[KBatchRequest alloc] initWithRequestArray:[array copy]];
    [request startWithCompletionBlockWithSuccess:^(KBatchRequest * _Nonnull batchRequest) {
        [weakSelf hideHUD];
        NSDictionary *bbsTopcs = bbsTopicsRequest.responseObject;
        NSInteger statusTopcs = [[bbsTopcs objectForKey:@"statusCode"] integerValue];
        if (statusTopcs == 200) {
            KLog(@"bbsTopcs:%@",bbsTopcs);
            weakSelf.topicViews = [KBbsTopicView modelWithDictionary:[bbsTopcs objectForKey:@"bbsTopicView"]];
            //标题
            weakSelf.titleLabel.text = weakSelf.topicViews.subject;
            //时间
            NSDate* date = [NSDate dateWithTimeIntervalSince1970:[weakSelf.topicViews.createTime integerValue]/1000];
            NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
            [fmt setDateFormat:@"dd-MM-yyyy HH:mm"];
            NSString* time = [NSString stringWithFormat:@"%@",[fmt stringFromDate:date]];
            weakSelf.timeLabel.text  = time;
            //点赞
            CGSize zanSize = [NSString sizeWithString:weakSelf.topicViews.likeNumber Size:CGSizeMake(kScreenWidth, 15) Font:15];
            weakSelf.zanLabel.height = zanSize.height;
            weakSelf.zanLabel.text = weakSelf.topicViews.likeNumber;
            weakSelf.zanBtn.x = kScreenWidth - 15 - 10 - 16 - zanSize.width;
            weakSelf.zanBtn.selected = [weakSelf.topicViews.isLike isEqualToString:@"Y"] ? YES : NO;
            //webview
            [weakSelf.webBaseView loadHtmlContentWithHtmlString:[weakSelf.topicViews.summary stringByReplacingOccurrencesOfString:@"\\" withString:@""]];
            [weakSelf.tableView reloadData];
        } else {
            [weakSelf showErrorText:[bbsTopcs objectForKey:@"msg"] errCode:statusTopcs];
        }
        if (self.isBbsPosts) {
            NSDictionary *bbsGeneralpost = bbsGeneralPostRequest.responseObject;
            NSInteger statusGeneral = [[bbsGeneralpost objectForKey:@"statusCode"] integerValue];
            if (statusGeneral == 200) {
                KLog(@"bbsGeneral:%@",bbsGeneralpost);
                [weakSelf.bbsPostsViews removeAllObjects];
                NSArray *arr = [bbsGeneralpost objectForKey:@"bbsPostsViews"];
                for (NSDictionary *tmp in arr) {
                    KBbsPostsViews *bbs = [KBbsPostsViews modelWithDictionary:tmp];
                    [weakSelf.bbsPostsViews addObject:bbs];
                }
                [weakSelf.tableView reloadData];
            } else {
                [weakSelf showErrorText:[bbsGeneralpost objectForKey:@"msg"] errCode:statusGeneral];
            }
        } else {
            NSDictionary *bbsGeneral = bbsGeneralRequest.responseObject;
            NSInteger statusGeneral = [[bbsGeneral objectForKey:@"statusCode"] integerValue];
            if (statusGeneral == 200) {
                KLog(@"bbsGeneral:%@",bbsGeneral);
                [weakSelf.bbsPostsViews removeAllObjects];
                NSArray *arr = [bbsGeneral objectForKey:@"bbsPostsViews"];
                for (NSDictionary *tmp in arr) {
                    KBbsPostsViews *bbs = [KBbsPostsViews modelWithDictionary:tmp];
                    [weakSelf.bbsPostsViews addObject:bbs];
                }
                [weakSelf.tableView reloadData];
            } else {
                [weakSelf showErrorText:[bbsGeneral objectForKey:@"msg"] errCode:statusGeneral];
            }
        }
        
    } failure:^(KBatchRequest * _Nonnull batchRequest) {
        [weakSelf hideHUD];
        [weakSelf showError:batchRequest.failedRequest.error];
    }];
}

- (void)getGeneralData {
    
    WEAKSELF
    KBbsGeneralDetailRequest *bbsGeneralRequest = [[KBbsGeneralDetailRequest alloc] init];
    bbsGeneralRequest.params = @{@"pageOn":@(pageNum),@"pageSize":@"10",@"topicId":self.bbsTopicViewsID};
    [bbsGeneralRequest startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
        NSDictionary *bbsGeneral = request.responseObject;
        NSInteger statusGeneral = [[bbsGeneral objectForKey:@"statusCode"] integerValue];
        if (statusGeneral == 200) {
            KLog(@"bbsGeneral:%@",bbsGeneral);
            NSArray *arr = [bbsGeneral objectForKey:@"bbsPostsViews"];
            for (NSDictionary *tmp in arr) {
                KBbsPostsViews *bbs = [KBbsPostsViews modelWithDictionary:tmp];
                [weakSelf.bbsPostsViews addObject:bbs];
            }
        } else {
            [weakSelf showErrorText:[bbsGeneral objectForKey:@"msg"] errCode:statusGeneral];
        }
    } failure:^(__kindof KBaseRequest * _Nonnull request) {
        [weakSelf hideHUD];
        [weakSelf showError:request.error];
    }];
}

- (IBAction)actionForZan:(id)sender {
    UIButton *btn = sender;
    if (btn.selected) {
        [self showText:@"Have thumb up!"];
        return;
    }
    kBbsGeneralDetailZanRequest *zanRequest = [[kBbsGeneralDetailZanRequest alloc] init];
    zanRequest.params = @{@"entityId":self.topicViews.id};
    WEAKSELF
    [zanRequest startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
        NSDictionary *dict = request.responseObject;
        NSInteger status = [[dict objectForKey:@"statusCode"] integerValue];
        if (status == 200) {
            [weakSelf showText:[dict objectForKey:@"msg"]];
            weakSelf.zanLabel.text = [NSString stringWithFormat:@"%d",[weakSelf.topicViews.likeNumber intValue] + 1];
            weakSelf.zanBtn.selected = YES;
        } else {
//            [weakSelf showText:[dict objectForKey:@"msg"]];
            [weakSelf showErrorText:[dict objectForKey:@"msg"] errCode:status];
        }
    } failure:^(__kindof KBaseRequest * _Nonnull request) {
        
    }];
}

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    CGFloat footerH = 60;
    
    self.headerView.frame=(CGRect){{0,0},{self.view.width,self.view.height/2}};
    self.titleLabel.frame = (CGRect){{15,20},{kScreenWidth - 30,34}};
    self.timeLabel.frame = (CGRect){{15,CGRectGetMaxY(self.titleLabel.frame) + 3},{200,15}};
    if (self.topicViews) {
        CGSize zanSize = [NSString sizeWithString:self.topicViews.likeNumber Size:CGSizeMake(kScreenWidth, 15) Font:15];
        self.zanLabel.height = zanSize.height;
        self.zanBtn.x = kScreenWidth - 15 - 10 - 16 - zanSize.width;
    } else {
        self.zanLabel.frame = (CGRect){{kScreenWidth - 25,CGRectGetMinY(self.timeLabel.frame)},{20,15}};
        self.zanBtn.frame = (CGRect){{kScreenWidth - 32 - 10 - 25,CGRectGetMinY(self.timeLabel.frame)},{16,16}};
        self.zanBtn.centerX = self.zanLabel.centerX;
    }
    self.webBaseView.frame=(CGRect){{0,CGRectGetMaxY(self.timeLabel.frame) + 20},{self.headerView.width,self.headerView.height}};
    self.tableView.frame=CGRectMake(0, 0, kScreenWidth, kScreenHeight - footerH - 64);
    self.tableView.tableHeaderView=self.headerView;
    
    CGFloat marginW= K_FactorW(15);
    CGFloat fieldH= K_FactorW(45);
    self.commentField.frame=(CGRect){{marginW,CGRectGetMaxY(self.tableView.frame)+(footerH-fieldH)/2},{self.view.width-2*marginW,fieldH}};
    self.commentField.layer.cornerRadius=self.commentField.height/2;
}
#pragma mark --UITableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.bbsPostsViews.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    KGeneralDetailViewCell*cell=[KGeneralDetailViewCell cellWithTableView:tableView];cell.delegate=self;
    KBbsPostsViews *bbs = [self.bbsPostsViews objectAtIndex:indexPath.row];
    cell.bbsPostsViews = bbs;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    KGeneralCommentsController *comments = [[KGeneralCommentsController alloc] init];
    KBbsPostsViews *bbs = [self.bbsPostsViews objectAtIndex:indexPath.row];
    comments.bbsPostID = bbs.id;
    [self.navigationController pushViewController:comments animated:YES];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    KBbsPostsViews *bbs = [self.bbsPostsViews objectAtIndex:indexPath.row];
    return bbs.cellHeight;
};
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView*headerView=[[UIView alloc]init];
    headerView.backgroundColor = [UIColor colorWithHexString:@"#f2f2f2"];
    UILabel*contentLabel=[[UILabel alloc]initWithFrame:CGRectMake(K_FactorW(0), 10, App_Frame_Width, K_FactorH(35))];
    contentLabel.text=@"  Comments";
    contentLabel.textColor=[UIColor colorWithHexString:@"#9a9a9a"];
    contentLabel.backgroundColor=[UIColor whiteColor];
    [headerView addSubview:contentLabel];
    return headerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return K_FactorH(45);
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    kBbsGeneralAndPost *andPost =  [[kBbsGeneralAndPost alloc] init];
    if (self.commentID) {
        andPost.params = @{@"content":textField.text,@"teachingLength":self.commentID,@"useExperience":@"notice"};
    } else {
        andPost.params = @{@"content":textField.text,@"topicId":self.topicViews.id,@"type":@"to_topic",@"useExperience":@"notice"};
    }
    
    WEAKSELF
    [andPost startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
        NSDictionary *dict = request.responseObject;
        NSInteger status = [[dict objectForKey:@"statusCode"] integerValue];
        [weakSelf hideHUD];
        if (status == 200) {
            weakSelf.commentField.text = nil;
            [weakSelf showSuccess:[dict objectForKey:@"msg"]];
            [weakSelf getData];
        } else {
            [weakSelf showErrorText:[dict objectForKey:@"msg"] errCode:status];
        }
    } failure:^(__kindof KBaseRequest * _Nonnull request) {
        [weakSelf hideHUD];
        [weakSelf showError:request.error];
    }];
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([string isEqualToString:@"\n"]) {
        [textField resignFirstResponder];
        return NO;
    }
    return YES;
}
 
#pragma mark --KGeneralDetailViewCellDelegate 评论的评论
-(void)generalDetailViewCellClickComment:(NSString *)general
{
    [self.commentField becomeFirstResponder];
    self.commentField.placeholder = @"Reply";
    self.commentID = general;
}
@end
